/*
 * 	class="js-lightBox" 			表示这个元素要启用lightbox标识
 *	data-role='lightBox' 			表示这个元素要启用lightbox标识
 *	data-src='img/1.jpg'  		图片的源地址
 *	data-desc='图片描述信息'  				图片描述信息
 *	data-id='1' 							图片的唯一标识
 *	data-group='group-1' 			图片的组别
 * 
 * eg:<img src="img/1.jpg" class="js-lightBox" data-role='lightBox' data-src='img/1.jpg' data-id='1' data-desc='1.jpg' data-group='group-1' />
 * 
 * 
 * 
 * 
 * */

;(function($){
	var MaxLightBox = function(config){
		var self = this;
		this.config    = $.extend(true, MaxLightBox.defaults, config);
		this.body      = $("body");																				//body
		this.win       = $('<div class="MaxLightBox"></div>');						//弹出层
		this.cover     = $('<div class="MaxLightBox-cover"></div>');			//遮罩层
		this.close     = $('<div class="MaxLightBox-cancel"></div>');			//关闭按钮
		this.groupName = null;																						//当前组别名称
		this.groupData = [];																							//当前组别的数据		
		this.index = 0;																										//当前图片在组别中的索引
		
		this._style();																										//插入插件样式
		this._template();																									//创建模版插入body
		
		this.content   = this.body.find('.MaxLightBox-con');							//内容区
		this.prevBtn   = this.body.find('.MLB-prev-btn');									//前一张
		this.nextBtn   = this.body.find('.MLB-next-btn');									//后一张
		this.imgView   = this.body.find('.MLB-view');											//图片
		this.pic			 = this.body.find('.MLB-pic');											//图片
		this.footer    = this.body.find('.MLB-foot');											//描述区
		this.desc      = this.body.find('.MLB-desc');											//描述内容
		this.indexCon  = this.body.find('.MLB-index');										//索引内容
		
		this.winWidth  = $(window).width();																//记录窗口的宽度
		this.winHeight = $(window).height();															//记录窗口的高度
		//获取数据
		this.body.on("click",this.config.lightBoxClass+",*[data-role="+this.config.dataRole+"]",function(){
			if($(this).attr("data-group") != self.groupName){
				self.groupName = $(this).attr("data-group");
				self.getGroupData();
			}
			//初始化弹窗
			self.initPopup($(this));
		})
		//事件绑定方法
		self.method();
	};
	
	//默认参数
	MaxLightBox.defaults = {
		lightBoxClass	:".js-lightBox",																		//插件触发的类样式标识
		dataRole			:"lightBox",																				//插件触发的data-role标识
		time					:500,																								//作用时间
		coverClose		:true																								//点击遮罩是否关闭，默认关闭
	};
	
	//插件原型方法
	MaxLightBox.prototype = {
		//事件绑定
		method:function(){
			var self = this;
			//按钮淡入淡出
			self.content.on("mouseenter",function(e){
				var ev = e || window.event;
				ev.stopPropagation();
				self.prevBtn.stop(true,false).fadeIn();
				self.nextBtn.stop(true,false).fadeIn();
			}).on("mouseleave",function(e){
				var ev = e || window.event;
				ev.stopPropagation();
				self.prevBtn.stop(true,false).fadeOut();
				self.nextBtn.stop(true,false).fadeOut();
			});
			
			//绑定向上按钮事件
			self.prevBtn.on("click",function(e){
				var ev = e || window.event;
				ev.stopPropagation();
				if($(this).hasClass("MLB-prev-btn-show")){
					self.index --;
					self.loadPic(self.groupData[self.index].src);
				}
			});
			
			//绑定向上按钮事件
			self.nextBtn.on("click",function(e){
				var ev = e || window.event;
				ev.stopPropagation();
				if($(this).hasClass("MLB-next-btn-show")){
					self.index ++;
					self.loadPic(self.groupData[self.index].src);
				}
			});
			//绑定遮罩层关闭事件
			if(self.config.coverClose){
				self.cover.on("click",function(e){
					var ev = e || window.event;
					ev.stopPropagation();
					self.win.fadeOut(500);
				});
			};
			
			//绑定关闭按钮的关闭事件
			self.close.on("click",function(e){
				var ev = e || window.event;
				ev.stopPropagation();
				self.win.fadeOut(500);
			});
			
			//窗口改变绑定事件
			$(window).on("resize",function(){
				clearTimeout(self.timer);
				self.timer = setTimeout(function(){
					self.winWidth = $(window).width();
					self.winHeight = $(window).height();
					self.loadPic(self.groupData[self.index].src);	
				},500)
			});
		},
		initPopup:function(curObj){
			var self = this
					curSrc = curObj.attr("data-src"),
					curId  = curObj.attr("data-id");
			self.showPopup(curSrc,curId)		
		},
		showPopup:function(src,id){
			var self = this;
			self.content.css({
				"width":"auto",
				"height":"auto",
			});
			self.pic.hide();
			self.footer.hide();
			self.win.fadeIn();
			//设置弹出窗的初识大小，窗口宽高的一半 
			self.content.css({
				"width":(self.winWidth / 2),
				"height":(self.winHeight / 2),
				"margin-left":- self.winWidth / 4,
				"margin-top":- self.winHeight 
			});
			//设置弹出窗的动画
			self.content.animate({
				"margin-top":- self.winHeight / 4
			},self.config.time,function(){
				//获取图片的尺寸
				self.loadPic(src);
			});
			//获取当前图片的索引
			self.getIndex(id);
			//控制图片切换按钮
			self.initBtn();
		},
		//载入图片
		loadPic:function(src){
			var self = this;
			self.initBtn();
			self.pic.hide().css({
				"width":"auto",
				"height":"auto"
			});
			self.footer.hide();
			//预载入图片
			this.prevLoadImg(src,function(){
				self.pic.attr("src",src).hide();
				//获取当前图片的原始尺寸
				var imgWidth  = self.pic.width(),
						imgHeight = self.pic.height();
				self.changePic(imgWidth,imgHeight);		
			});
		},
		changePic:function(imgWidth,imgHeight){
			var self = this;
			var scale = Math.min((self.winWidth / (imgWidth)),(self.winHeight / (imgHeight)),1);
			var newWidth = imgWidth * scale * 0.9;
			var newHeight = imgHeight * scale * 0.9;
			//修改内容区的宽高
			self.content.animate({
				"width":newWidth,
				"height":newHeight,
				"margin-left": - newWidth / 2,
				"margin-top":- newHeight / 2
			},self.config.time,function(){
				self.pic.css({
					"width":newWidth - 10,
					"height":newHeight - 10
				}).fadeIn();
				self.desc.text(self.groupData[self.index].desc);
				self.indexCon.text("当前索引："+(self.index + 1)+" of "+self.groupData.length);		
				self.footer.fadeIn();
			});
		},
		//图片预加载完成
		prevLoadImg:function(src,callback){
			var imgDom = new Image();
			if(!!window.ActiveXObject){//IE
				imgDom.onreadystatechange = function(){
					if(this.readyState == "complete"){
						if(callback){
							callback();
						}		
					}
				}
			}else{
				imgDom.onload = function(){
					if(callback){
						callback();
					}	
				}
			}
			imgDom.src = src;
		},
		//初始化按钮的显示状态
		initBtn:function(){
			var self = this,
					index = this.index;
			if(self.groupData.length<=1){
				self.prevBtn.removeClass("MLB-prev-btn-show");
				self.nextBtn.removeClass("MLB-next-btn-show");
				return ;
			}
			if(index == 0){
				self.prevBtn.removeClass("MLB-prev-btn-show");
				self.nextBtn.addClass("MLB-next-btn-show");
			}else if(index == (self.groupData.length - 1)){
				self.prevBtn.addClass("MLB-prev-btn-show");
				self.nextBtn.removeClass("MLB-next-btn-show");
			}else{
				self.prevBtn.addClass("MLB-prev-btn-show");
				self.nextBtn.addClass("MLB-next-btn-show");
			}
		},
		//获取当前图片在组别中的索引
		getIndex:function(id){
			var self = this;
			$(self.groupData).each(function(n){
				if(this.id === id){
					self.index = n;
					return false;
				}
			});
		},
		//获取当前组别的数据
		getGroupData:function(){
			var self = this;
			self.groupData = [];
			//根据组名存储数据
			var dataList = self.body.find("*[data-group="+self.groupName+"]");
			dataList.each(function(){
				//将组别数据以JSON格式插入到数组中
				self.groupData.push({
					src:$(this).attr("data-src"),
					id:$(this).attr("data-id"),
					desc:$(this).attr("data-desc"),
				});
			});
		},
		//初始化模版
		_template:function(){
			var html ='<div class="MaxLightBox-con">'+
								'	<span class="MLB-btn MLB-prev-btn"></span>'+
								'	<span class="MLB-btn MLB-next-btn"></span>'+
								'	<div class="MLB-view">'+
								'		<img class="MLB-pic">'+
								'	</div>'+
								'	<div class="MLB-foot">'+
								'		<div class="MLB-desc">123</div>'+
								'		<div class="MLB-index">当前索引：0 of 0</div>'+
								'	</div>'+
								'</div>';
			this.win.append(this.cover,this.close,html);					
			this.body.append(this.win);
		},
		//初始化样式
		_style:function(){
			var headStyle = $(document).find("head");
			if($("style.MaxLightBox-css").length==0){
				var sty = '<style class="MaxLightBox-css">'+
									'	.MaxLightBox{position:fixed;top:0;left:0;width:100%;height:100%;display:none;}'+
									'	.MaxLightBox .MaxLightBox-cancel{position:absolute;top:10px;right:10px;width:27px;height:27px;background-image:url("");cursor:pointer;}'+
									'	.MaxLightBox .MaxLightBox-cover{position:absolute;left:0;top:0;width:100%;height:100%;background-color:#000;background-color:rgba(0,0,0,.5);filter:Alpha(Opacity=50);}'+
									'	.MaxLightBox .MaxLightBox-con{position:absolute;top:50%;left:50%;color:#333;background:#fff;background-image:url("");background-repeat:no-repeat;background-position:center;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-btn{position:absolute;top:0;height:100%;width:25%;display:inline-block;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-prev-btn{left:0;background-repeat:no-repeat;background-position:left center;background-origin:border-box;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-prev-btn-show{display:none;background-image:url("");cursor:pointer;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-next-btn{right:0;background-repeat:no-repeat;background-position:right center;background-origin:border-box;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-next-btn-show{display:none;background-image:url("");cursor:pointer;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-view{width:100%;height:100%;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-view>img.MLB-pic{border:5px solid #fff;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-foot{position:absolute;bottom:0;left:0;right:0;margin:5px;background:url("");color:#fff;display:none;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-desc{margin:6px;}'+
									'	.MaxLightBox .MaxLightBox-con .MLB-index{color:#ddd;margin:6px;}'+
									'</style>';
				headStyle.append(sty);
			}
		}
	};
	
	$.MaxLightBox = function(config){
		return new MaxLightBox(config);
	};
	
})(jQuery);